import React from 'react'
import { connect } from 'dva'
import router from 'umi/router'
import { formatMessage } from 'umi/locale'
import { Input } from 'antd'
import PageHeaderWrapper from '@/components/PageHeaderWrapper'

@connect(({ staffHall, user }) => ({
  staffHall,
  user
}))
class StaffHall extends React.PureComponent {

  state = {
    // 默认显示我的列表
    tabActiveKey: 'my'
  }

  componentDidMount() {
    const { dispatch } = this.props

    // 获取部门列表 用于 tab显示
    dispatch({
      type: 'user/fetchDepartment'
    })
  }

  // 导航默认切换
  handleTabChange = key => {
    const { dispatch, match } = this.props

    const payload = {}
    if (key === 'my') {
      router.push(`${match.url}/my`)

      Object.assign(payload, {
        page: 0
      })
    } else {
      router.push(`${match.url}/search`)
      
      Object.assign(payload, {
        pageNumber: 1
      })
    }

    if (key !== 'search' && key !== 'my') {
      Object.assign(payload, {
        department_id: key,
      })
    }

    this.setState(state => ({
      ...state,
      tabActiveKey: key
    }), () => {
      dispatch({
        type: 'staffHall/changeTab',
        payload
      })
    })
  }

  // 搜索 默认跳转到全部
  handleFormSubmit = values => {
    const { dispatch, match } = this.props

    router.push(`${match.url}/search`)

    const payload = { pageNumber: 1 }
    if (values) {
      Object.assign(payload, {
        staff_name: values
      })
    }
    dispatch({
      type: 'staffHall/fetchStaff',
      payload
    })
  }

  render() {

    const { tabActiveKey } = this.state
    const { user, children } = this.props
    const { department = [] } = user

    const tabList = [{
      key: 'my',
      tab: formatMessage({ id: 'menu.staff.my' }, {})
    }, {
      key: 'search',
      tab: formatMessage({ id: 'menu.staff.search' }, {})
    }]

    department.forEach(item => {
      tabList.push({
        key: item.department_id,
        tab: item.department_name,
      })
    })

    const mainSearch = (
      <div style={{ textAlign: 'center' }}>
        <Input.Search
          placeholder="请输入要搜索的员工姓名"
          enterButton="搜索"
          size="large"
          onSearch={this.handleFormSubmit}
          style={{ maxWidth: 522 }}
        />
      </div>
    )

    return (
      <PageHeaderWrapper
        content={mainSearch}
        tabList={tabList}
        tabActiveKey={tabActiveKey}
        onTabChange={this.handleTabChange}
      >
        {children}
      </PageHeaderWrapper>
    )
  }
}

export default StaffHall